﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Windows;
using System.Windows.Documents;
using FirstFloor.ModernUI.Presentation;
using FirstFloor.ModernUI.Windows.Controls;
using IsikFx.Project.ClientApp.Helpers;
using IsikFx.Project.CommonTypes.User;
using log4net;
namespace IsikFx.Project.ClientApp
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : ModernWindow
    {
        public static ILog logger = LogManager.GetLogger(typeof(MainWindow));
        public MainWindow()
        {
            try
            {
                InitializeComponent();
                Helper.InitializeCurrentUser();
                if (CheckFirstLogin())
                {
                    this.ContentSource = new Uri("/Pages/FirstLogin.xaml", UriKind.Relative);
                }

                GetLinksOnWindow();
            }

            catch (Exception ex)
            {
                logger.Error(ex.Message);
                logger.Error(ex.StackTrace);
                MessageBox.Show("Veritabanı bağlantısı sağlanamadı.");
                Thread.Sleep(5000);
                Process.GetCurrentProcess().Kill();
            }
        }

        private bool CheckFirstLogin()
        {
            IsikFxWcfService.ServiceClient client = new IsikFxWcfService.ServiceClient();
            return client.CheckFirstLogin(Environment.UserDomainName + "_" + Environment.UserName);
        }

        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
        }

        private void GetLinksOnWindow()
        {
            List<Link> links = this.MenuLinkGroups[0].Links.ToList();

            User CurrentUser = Helper.CurrentUser;
            if (CurrentUser != null)
            {
                foreach (Link link in links)
                {
                    if (Helpers.Helper.CurrentUser.RoleType == ((int)Helpers.Helper.Roles.Admin))
                    {
                        if (!link.Source.ToString().Contains("Admin") && !link.Source.ToString().Contains("Setting"))
                        {
                            (this.MenuLinkGroups[0].Links).Remove(link);
                        }
                    }
                    else
                    {
                        if (link.Source.ToString().Contains("Admin"))
                        {
                            (this.MenuLinkGroups[0].Links).Remove(link);
                        }
                    }
                    this.ContentSource = this.MenuLinkGroups[0].Links[0].Source;
                }

            }
            else
            {
                MessageBox.Show("Hata user alınamadı");
            }
        }
    }
}
